package nayasis.common.db.manager.transaction;

import java.util.List;

import nayasis.common.context.ContextThreadLocal;
import nayasis.common.db.manager.connection.WrapperConnection;


/**
 * 데이터베이스 트렌젝션을 관리한다.
 *
 * @author nayasis
 *
 */
public final class TxManager {

	private static final String KEY_TX_BEGIN = "nayasis.common.db.manager.TxManager.txBeginGlobal";

	private TxManager() {}

	/**
	 * 트렌젝션을 시작한다.
	 */
	public static void beginTransaction() {

		if( ! isTransactionWorking() ) {
			ContextThreadLocal.set( KEY_TX_BEGIN, true );
		}

	}

	/**
	 * 트렌젝션이 관리중인 상태인지 여부를 확인한다.
	 *
	 * @return 트렌젝션 상태 여부
	 */
	public static boolean isTransactionWorking() {

		return ContextThreadLocal.containsKey( KEY_TX_BEGIN );

	}

	/**
	 * 트렌젝션을 중지한다.
	 */
	public static void stopTransaction() {

	    if( ! isTransactionWorking() ) return;

		ContextThreadLocal.remove( KEY_TX_BEGIN );

		List<WrapperConnection> connList = ConnectionThreadLocal.getConnectionList();

		for( WrapperConnection conn : connList ) {
			ConnectionThreadLocal.remove( conn );
		}

	}

	/**
	 * 데이터를 commit 한다.
	 */
	public static void commit() {

	    if( ! isTransactionWorking() ) return;

		List<WrapperConnection> connList = ConnectionThreadLocal.getConnectionList();

		for( WrapperConnection conn : connList ) {
			conn.commit();
		}

	}

	/**
	 * 데이터를 rollback 한다.
	 */
	public static void rollback() {

	    if( ! isTransactionWorking() ) return;

		List<WrapperConnection> connList = ConnectionThreadLocal.getConnectionList();

		for( WrapperConnection conn : connList ) {
			conn.rollback();
		}

	}

}
